package com.csht.facelib.utils;

import android.content.Context;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import com.csht.facelib.api.FaceSdk;

import java.net.NetworkInterface;
import java.net.SocketException;
import java.security.MessageDigest;
import java.util.UUID;

/**
 * Created by Administrator on 2019/3/14 0014.
 */

public class DeviceIdUtils {

    /**
     * 获取设备唯一标识符
     *
     * @return
     */
    public static String getDeviceId() {
//        return "2040980P03401643";
        Context context = FaceSdk.getInstance().getContext();
        //读取保存的在sd卡中的唯一标识符
        String deviceId = readDeviceID(context);
        if (!TextUtils.isEmpty(deviceId)) {
            return deviceId;
        }

        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                deviceId = Build.getSerial();
            }else {
                deviceId = Build.SERIAL;
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        try {
            if (TextUtils.isEmpty(deviceId)|| Build.UNKNOWN.equals(deviceId)) {
                //获取IMES(也就是常说的DeviceId)
                deviceId = getIMIEStatus(context);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            if (TextUtils.isEmpty(deviceId)|| Build.UNKNOWN.equals(deviceId)) {
                //获取设备的MACAddress地址 去掉中间相隔的冒号
                deviceId = getLocalMac().replace(":", "");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
//        }

        //如果以上搜没有获取相应的则自己生成相应的UUID作为相应设备唯一标识符
        if (TextUtils.isEmpty(deviceId) || Build.UNKNOWN.equals(deviceId)) {
            UUID uuid = UUID.randomUUID();
            deviceId = uuid.toString().replace("-", "");
            if (!TextUtils.isEmpty(deviceId)&&deviceId.length()>16){
                deviceId = deviceId.substring(0,16);
            }
        }

        saveDeviceID(deviceId, context);
        return deviceId;
    }


    /**
     * 读取固定的文件中的内容,这里就是读取sd卡中保存的设备唯一标识符
     *
     * @return
     */
    private static String readDeviceID(Context context) {
        try {
            return context.getSharedPreferences("deviceId", Context.MODE_PRIVATE).getString("deviceId","");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取设备的DeviceId(IMES) 这里需要相应的权限<br/>
     * 需要 READ_PHONE_STATE 权限
     *
     * @param context
     * @return
     */
    private static String getIMIEStatus(Context context) {
        try {
            TelephonyManager tm = (TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);
            return tm.getDeviceId();
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 获取设备MAC 地址 由于 6.0 以后 WifiManager 得到的 MacAddress得到都是 相同的没有意义的内容
     * 所以采用以下方法获取Mac地址
     * @return
     */
    private static String getLocalMac() {
//        WifiManager wifi = (WifiManager) context
//                .getSystemService(Context.WIFI_SERVICE);
//        WifiInfo info = wifi.getConnectionInfo();
//        return info.getMacAddress();


        String macAddress = null;
        StringBuffer buf = new StringBuffer();
        NetworkInterface networkInterface = null;
        try {
            networkInterface = NetworkInterface.getByName("eth1");
            if (networkInterface == null) {
                networkInterface = NetworkInterface.getByName("wlan0");
            }
            if (networkInterface == null) {
                return "";
            }
            byte[] addr = networkInterface.getHardwareAddress();


            for (byte b : addr) {
                buf.append(String.format("%02X:", b));
            }
            if (buf.length() > 0) {
                buf.deleteCharAt(buf.length() - 1);
            }
            macAddress = buf.toString();
        } catch (SocketException e) {
            e.printStackTrace();
            return "";
        }
        return macAddress;


    }

    /**
     * 保存 内容到 SD卡中,  这里保存的就是 设备唯一标识符
     * @param str
     * @param context
     */
    private static void saveDeviceID(String str, Context context) {
        try {
            context.getSharedPreferences("deviceId", Context.MODE_PRIVATE).edit().putString("deviceId",str).apply();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 对挺特定的 内容进行 md5 加密
     * @param message  加密明文
     * @param upperCase  加密以后的字符串是是大写还是小写  true 大写  false 小写
     * @return
     */
    private static String getMD5(String message, boolean upperCase) {
        String md5str = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");

            byte[] input = message.getBytes();

            byte[] buff = md.digest(input);

            md5str = bytesToHex(buff, upperCase);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return md5str;
    }


    private static String bytesToHex(byte[] bytes, boolean upperCase) {
        StringBuilder md5str = new StringBuilder();
        int digital;
        for (byte aByte : bytes) {
            digital = aByte;

            if (digital < 0) {
                digital += 256;
            }
            if (digital < 16) {
                md5str.append("0");
            }
            md5str.append(Integer.toHexString(digital));
        }
        if (upperCase) {
            return md5str.toString().toUpperCase();
        }
        return md5str.toString().toLowerCase();
    }
}

